package it.uniroma3.dia.ia.textcategorization.datasource.odpdump;

import java.util.HashSet;
import java.util.Set;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public final class LinksCollectorHandler extends DefaultHandler {

	private String path;
	private Set<String> links;

	private boolean matchingCategoryFound = false;

	LinksCollectorHandler(String path) {
		this.path = path;
		this.links = new HashSet<String>();
	}

	@Override
	public void startElement(String uri, String localName, String qualifiedName,
			Attributes attributes) {
		if (qualifiedName.equals("Topic")) {
			String categoryName = attributes.getValue("r:id");
			if (categoryName.startsWith(this.path)) {
				this.matchingCategoryFound = true;
			}
		} else if (qualifiedName.equals("link") || qualifiedName.equals("link1")) {
			if (this.matchingCategoryFound) {
				String link = attributes.getValue("r:resource");
				this.links.add(link);
			}
		}
	}

	@Override
	public void endElement(String uri, String localName, String qualifiedName) {
		if (qualifiedName.equals("Topic")) {
			if (this.matchingCategoryFound) {
				this.matchingCategoryFound = false;
			}
		}
	}

	Set<String> getLinks() {
		return this.links;
	}

}
